<?php

namespace app\api\controller;

use app\common\model\Login as loginModel;
use app\common\controller\Api;
use app\common\model\User as UserModel;
class Login extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->loginModel   = new loginModel();
        $this->modelUser   = new UserModel();
        if (config('site.miniapp')) {
            $this->miniapp_AppID     = config('site.miniapp_AppID');
            $this->miniapp_AppSercet = config('site.miniapp_AppSecret');
            $this->miniappLoginUrl   = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->miniapp_AppID}&secret={$this->miniapp_AppSercet}";
        }
        if (config('site.wx_mp')) {
            $this->mp_AppID     = config('site.mp_AppID');
            $this->mp_AppSecret = config('site.mp_AppSecret');
            $this->mpLoginUrl   = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->mp_AppID}&secret={$this->mp_AppSecret}";
        }
    }

    /**
     * 小程序/公众号/App 登录
     * @return void
     */
    public function login()
    {
        $param  = $this->request->param();
        $this->validateCommon('Login.login', $this->serial_number);
        if ($param['loginType'] == 1) {
            if (!$param['miniappLoginCode']) $this->error('小程序未获取登录权限', '', 0, $this->serial_number);
            $param['loginTypeDevice'] = 'miniapp';
            $param['appID']           = $this->miniapp_AppID;
            $param['appSercet']       = $this->miniapp_AppSercet;
            $param['loginUrl']        = $this->miniappLoginUrl . "&js_code={$param['miniappLoginCode']}&grant_type=authorization_code";
        }
        if ($param['loginType'] == 2) {
            if (!$param['mpLoginCode']) $this->error('公众号未获取登录权限', '', 0, $this->serial_number);
            $param['loginTypeDevice'] = 'mp';
            $param['appID']           = $this->mp_AppID;
            $param['appSercet']       = $this->mp_AppSecret;
            $param['loginUrl']        = $this->mpLoginUrl . "&code={$param['mpLoginCode']}&grant_type=authorization_code";
        }
        if ($param['loginType'] == 3) {
            $param['loginTypeDevice'] = 'app';
        }
        $result = $this->loginModel->loginInfo($param);
        if ($result['status'] == 0) $this->error($result['msg'], '', 0, $this->serial_number);
        //判断是否登录或注册
        if ($param['loginTypeDevice'] == 'miniapp') $whereDevice['miniAppOpenId'] = $result['data']['miniAppOpenId'];
        if ($param['loginTypeDevice'] == 'mp') $whereDevice['mpOpenId'] = $result['data']['mpOpenId'];
        if ($param['loginTypeDevice'] == 'app') $whereDevice['appOpenId'] = $result['data']['appOpenId'];
        $field = "id as userId,username as userName,money as userMoney,token,mobile as userMobile,avatar as userAvatar";
        if ($result['data']['unionid']) {
            $getUserInfo = $this->modelUser->where(['unionid' => $result['data']['unionid']])->field($field)->find();
        } else {
            $getUserInfo = $this->modelUser->where($whereDevice)->field($field)->find();
        }
        if ($getUserInfo) {
            $ret = $this->auth->direct($getUserInfo['userId']);
        } else {
            $sex      = $result['data']['sex'] ? $result['data']['sex'] : 1;
            $avatar   = $result['data']['avatar'] ? $result['data']['avatar'] : config('site.avatar');
            $username = $result['data']['userName'] ? $result['data']['userName'] : nickname(1);
            if(isset($param['avatar']) && !empty($param['avatar'])) $avatar = $param['avatar'];
            if(isset($param['userName']) && !empty($param['userName'])) $username = $param['userName'];
                $extend   = [
                'unionid'       => $result['data']['unionid'],
                'appOpenId'     => $result['data']['appOpenId'],
                'mpOpenId'      => $result['data']['mpOpenId'],
                'miniAppOpenId' => $result['data']['miniAppOpenId'],
                'sex'           => $sex,
                'avatar'        => $avatar,
            ];
            $ret      = $this->auth->register($username, 123456, '', $result['data']['mobile'] ?? '', $extend);
        }
        if ($ret) {
            $data                             = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data, 1, $this->serial_number);
        } else {
            $this->error($this->auth->getError(), '', 0, $this->serial_number);
        }
    }
}